package com.itheima.demo;

import com.itheima.domain.Person;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/7/19 12:46
 */
public class Demo_XML_001 {
    public static void main(String[] args) throws DocumentException {
        //1.获取一个解析器对象
        SAXReader sr = new SAXReader();
        //2.利用解析器把xml文件加载到内存中,并返回一个文档对象
        Document document = sr.read(new File("demo_xml\\xml\\Person.xml"));
        //3.获取到根标签
        Element element = document.getRootElement();
        //4.通过根标签来获取Person标签
        List<Element> personElement = element.elements("person");
        //创建一个存放封装数据的集合 ;
        ArrayList<Person> list = new ArrayList<>();
        //5.遍历集合,得到每一个Person标签
        for (Element elements : personElement) {
            //获取id这个属性
            Attribute idElement = elements.attribute("id");
            //获取属性的值 ;
            String id = idElement.getValue();
            //获取name标签
            //element("标签名"):获取调用者指定的子标签
            Element nameElement = elements.element("name");
            //获取姓名的内容;
            String name = nameElement.getText();

            //获取年龄的标签
            Element ageElement = elements.element("age");
            //获取年龄的值 ;
            String age = ageElement.getText();

            //获取电话的标签 ;
            Element tellPhoneElement = elements.element("tellPhone");
            //获取电话的值;
            String tellPhone = tellPhoneElement.getText();

            //将这些数据封装到Person对象,然后添加到集合当中 ;
            Person p = new Person(id,name,Integer.parseInt(age),tellPhone);

            list.add(p);
        }

        //遍历集合;
        for (Person person : list) {
            System.out.println(person);
        }

    }
}
